/**
 * JAVACC DEMO 1.0
 */
package com.apache.uct.service.plugins;

import com.apache.api.manager.PluginConnector;
import com.apache.api.manager.ProxyManager;
import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.tools.ClassToolsUtil;
import com.apache.tools.DateUtils;
import com.apache.tools.TreeNode;
import com.apache.uct.common.entity.Act;
import com.apache.uct.manager.ActManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * description:  资源管理Action插件
 *
 * @author iussoft 创建时间：2016-4-1
 */
public class ActActionPluginImpl implements PluginConnector {

    private Logger log = LoggerFactory.getLogger(ActActionPluginImpl.class);

    private ActManager actManager;

    private ProxyManager uctProxyManager;

    /**
     * TODO 机构属性查询插件(按权限ID或英文全称).<br>
     * 参数说明:<br>
     * propertyName:属性名称<br>
     * propertyValue:属性值
     */
    public Object execute(ParamsVo vo) throws Exception {
        ResultEntity result = new ResultEntity();
        result.setResult("true");
        String key = String.valueOf(vo.getParams("method"));
        if ("save".equalsIgnoreCase(key)) {//createUser,reqIp,(act)
            save(result, vo);
        } else if ("delete".equalsIgnoreCase(key)) {//createUser,reqIp,id
            deleteInfo(result, vo);
        } else if ("tree".equalsIgnoreCase(key)) {//id,sysEname,actId
            actTree(result, vo);
        } else if ("byId".equalsIgnoreCase(key)) {
            ParamsVo<Act> param = new ParamsVo<Act>();
            param.setInfoId(String.valueOf(vo.getParams("actId")));
            result.setEntity(actManager.getInfoById(param));
            result.setMessage("查询成功");
        }
        return result;
    }

    private void save(ResultEntity result, ParamsVo vo) {
        ParamsVo<Act> param = new ParamsVo<Act>();
        Act item = new Act();
        item = (Act) ClassToolsUtil.getInstance().convert2Bean(vo.getParams(), item);
        long times = DateUtils.toLong(new Date());
        String userEname = String.valueOf(vo.getParams("createUser"));
        param.setLogIp(String.valueOf(vo.getParams("reqIp")));
        param.setLogClassName(Act.class.getName());
        param.setUserEname(userEname);
        if (Validator.isNotNull(item.getActId())) {//对权限信息修改
            item.setUpdateTime(times);
            item.setUpdateUser(userEname);
            buildAct(item);
            param.setObj(item);
            boolean mark = actManager.editInfo(param);
            if (!mark) {
                result.setMessage("信息修改失败！");
            } else {
                result.setEntity("true");
                result.setMessage("信息修改成功！");
            }
        } else {//添加角色信息
            item.setCreateUser(userEname);
            item.setUpdateCount(0);
            item.setCreateTime(times);
            buildAct(item);
            param.setObj(item);
            param.setKey("checkActEname");
            String flag = String.valueOf(actManager.execute(param));
            if ("true".equals(flag)) {
                String id = actManager.saveInfo(param);
                if (Validator.isNull(id)) {
                    result.setMessage("信息添加失败！");
                } else {
                    result.setEntity("true");
                    result.setMessage("信息添加成功！");
                }
            } else {
                result.setMessage("权限标识已存在,操作失败！");
            }
        }
    }

    private void deleteInfo(ResultEntity result, ParamsVo vo) {
        ParamsVo<Act> param = new ParamsVo<Act>();
        String userEname = String.valueOf(vo.getParams("createUser"));
        param.setLogIp(String.valueOf(vo.getParams("reqIp")));
        param.setLogClassName(Act.class.getName());
        param.setUserEname(userEname);
        String id = String.valueOf(vo.getParams("id"));
        if (Validator.isNotNull(id)) {
            param.setInfoId(id);
            param.setKey("deleteOrg");
            param.setParams("infoType", "act");
            String msg = String.valueOf(uctProxyManager.doInvoke(param));
            if (Validator.isNotNull(msg)) {
                result.setMessage(msg);
            } else {
                result.setEntity("true");
                result.setMessage("信息删除成功！");
            }
        } else {
            result.setMessage("请选择要删除的资源！");
        }
    }

    private void actTree(ResultEntity result, ParamsVo param) {
        net.sf.json.JSONArray jary = new net.sf.json.JSONArray();
        String id = Validator.getDefaultStr(String.valueOf(param.getParams("id")), "0");
        String sysEname = Validator.getDefaultStr(String.valueOf(param.getParams("sysEname")), "");
        ParamsVo<Act> pvo = new ParamsVo<Act>();
        Act act = new Act();
        act.setFatherId(id);
        act.setSysEname(sysEname);
        pvo.setObj(act);
        List<Act> actList = actManager.getList(pvo);
        if (Validator.isEmpty(actList)) {
            result.setEntity(jary);
            return;
        }
        String fullEname = "";
        String actId = String.valueOf(param.getParams("actId"));
        if ("0".equals(id) && Validator.isNotNull(actId)) {
            pvo = new ParamsVo<Act>();
            pvo.setInfoId(actId);
            Act avo = (Act) actManager.getInfoById(pvo);
            if (null != avo) {
                fullEname = avo.getFullEname();
            }
        }
        for (int i = 0; i < actList.size(); i++) {
            Act vo = actList.get(i);
            //			TreeNode tvo = toTreeVo(vo);
            //			if (StrUtil.isNotNull(fullEname)) {
            //				//如果当前id在默认选中值的家族中，则构造树，并展开
            //				if (fullEname.startsWith(vo.getFullEname())) {
            //					tvo = getSubTree(tvo, vo, fullEname);
            //					tvo.setState("opened");
            //				}
            //			}
            jary.add(vo);
        }
        result.setEntity(jary);
    }

    /**
     * 将Act转成程TreeNode
     *
     * @param vo
     * @return TreeNode
     */
    private TreeNode toTreeVo(Act vo) {
        TreeNode tvo = new TreeNode();
        tvo.setChecked("checked");
        tvo.setIconCls("");
        if (vo.getSubCount() > 0) {
            tvo.setState("closed");
        } else {
            tvo.setState("opened");
        }
        tvo.setId(vo.getActId());
        tvo.setText(vo.getActCname());
        return tvo;
    }

    /**
     * 递归查询所有子节点
     *
     * @param treeNode
     * @param act
     * @param fullEname
     * @return TreeNode
     */
    private TreeNode getSubTree(TreeNode treeNode, Act act, String fullEname) {
        ParamsVo<Act> pvo = new ParamsVo<Act>();
        Act actvo = new Act();
        actvo.setFatherId(act.getActId());
        pvo.setObj(actvo);
        List<Act> list = actManager.getList(pvo);
        List<TreeNode> children = new ArrayList<TreeNode>();
        if (list != null && list.size() > 0) {
            for (int i = 0; i < list.size(); i++) {
                Act vo = list.get(i);
                TreeNode tvo = toTreeVo(vo);
                if (fullEname.startsWith(vo.getFullEname())) {
                    tvo.setState("opened");
                }
                children.add(getSubTree(tvo, vo, fullEname));
            }
        }
        treeNode.setChildren(children);
        return treeNode;
    }

    public void setActManager(ActManager actManager) {
        this.actManager = actManager;
    }

    public void setUctProxyManager(ProxyManager uctProxyManager) {
        this.uctProxyManager = uctProxyManager;
    }

    /**
     * 组织权限数据
     */
    private void buildAct(Act item) {
        if (Validator.isNull(item.getFullEname())) {
            if (!"0".equals(item.getFatherId())) {
                ParamsVo<Act> pvo = new ParamsVo<Act>();
                pvo.setInfoId(item.getFatherId());
                Act act = (Act) actManager.getInfoById(pvo);
                item.setFullEname(
                        Validator.getDefaultStr(act.getFullEname(), act.getActEname()) + "/" + item
                                .getActEname());
                item.setFullCname(act.getActCname() + "/" + item.getActCname());
                item.setSysEname(act.getSysEname());
            } else {
                item.setFullEname("/" + item.getActEname());
                item.setFullCname("/" + item.getActCname());
            }
        }
    }

}
